//
//  wmimaViewController.m
//  hainingOASystem
//
//  Created by michael on 2017/12/12.
//  Copyright © 2017年 czd. All rights reserved.
//
#import "myView.h"
#import "Toast+UIView.h"
#import "UIViewExt.h"
#import "mimaViewController.h"
#import <CommonCrypto/CommonDigest.h>
#import "Masonry.h"
#import "wmimaViewController.h"
#import "OALoginViewController.h"

static int countDownTime = 180;

@interface wmimaViewController ()

@end

@implementation wmimaViewController

- (void)viewDidLoad {
    [super viewDidLoad];
         self.navigationController.navigationBar.tintColor = [UIColor whiteColor];
self.title = @"忘记密码";
NSDictionary *attributes = [NSDictionary dictionaryWithObjectsAndKeys:

[UIColor whiteColor],NSForegroundColorAttributeName, nil];
 
[self.navigationController.navigationBar setTitleTextAttributes:attributes];
 self.navigationController.navigationBar.barTintColor = COLORRGB(0x3F51B5);;
    self.view.backgroundColor = [UIColor whiteColor];//    [self initview];
//  [self config];
    //
    [self layoutRootViewControllerSubviews];
       //点击手势

UIBarButtonItem *item1 = [[UIBarButtonItem alloc] initWithTitle:@"返回"style:UIBarButtonItemStylePlain target:self action:@selector(buttonClick)];
 self.navigationItem.leftBarButtonItem = item1;

//    [self createTextFields];

    // Do any additional setup after loading the view.
}
- (void)buttonClick{
      UIStoryboard * storyBoard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];

        OALoginViewController * loginVC = [storyBoard instantiateViewControllerWithIdentifier:@"LoginVC"];
        UINavigationController * navVC = [[UINavigationController alloc]initWithRootViewController:loginVC];
    self.view.window.rootViewController = navVC;
        loginVC.navigationController.navigationBar.hidden = YES;


}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
#pragma mark - 布局
- (void)layoutRootViewControllerSubviews{
    __weak typeof(self) weak_self = self;
    

                  _name.keyboardType = UIKeyboardTypeASCIICapable;

              _originPassword.keyboardType = UIKeyboardTypeNumberPad;
              _resetPassword.keyboardType = UIKeyboardTypeASCIICapable;
              _repetNewPassword.keyboardType = UIKeyboardTypeASCIICapable;
[_resetPassword setSecureTextEntry:YES];
[_repetNewPassword setSecureTextEntry:YES];
    [weak_self.flagSuperView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(weak_self.view);
    }];
    //
    
    
    [weak_self.name mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(weak_self.flagSuperView.mas_top).offset(kNavgationBarHeight + 30 * kViewSizeScale);
        make.left.mas_equalTo(weak_self.flagSuperView.mas_left).offset(10 * kViewSizeScale);
        make.right.mas_equalTo(weak_self.flagSuperView.mas_right).offset(-10 * kViewSizeScale);
        make.height.mas_equalTo(44 * kViewSizeScale);
    }];
    [weak_self.originPassword mas_makeConstraints:^(MASConstraintMaker *make) {
       
        make.top.mas_equalTo(weak_self.name.mas_bottom).offset(20 * kViewSizeScale);
        make.left.right.height.equalTo(weak_self.name);
//     make.top.mas_equalTo(weak_self.flagSuperView.mas_top).offset(kNavgationBarHeight + 30 * kViewSizeScale);
//        make.left.mas_equalTo(weak_self.flagSuperView.mas_left).offset(10 * kViewSizeScale);
//        make.right.mas_equalTo(weak_self.flagSuperView.mas_right).offset(-10 * kViewSizeScale);
//        make.height.mas_equalTo(44 * kViewSizeScale);
    }];
    
       _yanzbutton = [myView creatButtonWithFrame:CGRectMake(_originPassword.right-100, 0,100,44 * kViewSizeScale) title:@"获取验证码" tag:1000 tintColor:[UIColor whiteColor] backgroundColor:COLORRGB(0x3F51B5)];
        _yanzbutton.layer.cornerRadius = 10;
        _yanzbutton.font = [UIFont systemFontOfSize:14];
        [_yanzbutton addTarget:self action:@selector(getVerificationCode) forControlEvents:UIControlEventTouchUpInside];
        [_originPassword addSubview:_yanzbutton];
    //
    [weak_self.resetPassword mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(weak_self.originPassword.mas_bottom).offset(20 * kViewSizeScale);
        make.left.right.height.equalTo(weak_self.originPassword);
    }];
    //
    [weak_self.repetNewPassword mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(weak_self.resetPassword.mas_bottom).offset(20 * kViewSizeScale);
        make.left.right.height.equalTo(weak_self.originPassword);
    }];
    //
    [weak_self.loginButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(weak_self.repetNewPassword.mas_bottom).offset(30 * kViewSizeScale);
        make.centerX.equalTo(weak_self.flagSuperView.mas_centerX);
        make.size.mas_equalTo(CGSizeMake(kMainScreenW/2, 50 * kViewSizeScale));
    }];
}
- (void)getVerificationCode
{
NSString *oldstring=[_name.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
if ([oldstring isEqualToString:@""]|| oldstring.length == 0) {
        [self.view makeToast:@"请输入用户名"];
}else{



    _label = [[UILabel alloc]initWithFrame:self.yanzbutton.bounds];
    
    _timer = [[NSTimer alloc]init];
    _timer= [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(countDown) userInfo:nil repeats:YES];
    [_timer setFireDate:[NSDate distantPast]];
    //请求服务器发送短信验证码
    //......
    
    NSString *url = [NSString stringWithFormat:@"%@%@",kyanz,oldstring];
       [httpTool ZBPostNetDataWith:url withDic:nil andSuccess:^(NSDictionary* dictionary){
       if ([[NSString stringWithFormat:@"%@",dictionary[@"success"]]isEqualToString:@"true"]) {
           [self .view makeToast:dictionary[@"msg"]];
_codeId = dictionary[@"codeId"];
}else{

        [self.view makeToast:@"用户名错误!"];

}
       }andFailure:^{

        [self.view makeToast:@"用户名错误!"];

 }];
}
}
- (void)countDown
{
    countDownTime--;
    if (countDownTime<=0||countDownTime ==180) {
        _label.hidden = YES;
        _yanzbutton.hidden = NO;
        _yanzbutton.userInteractionEnabled = YES;
        [_timer setFireDate:[NSDate distantFuture]];
        countDownTime =180;
    }else{

        _label.hidden = NO;
        _label.text = [NSString stringWithFormat:@"(%ds)重新获取",countDownTime];
        _label.font = [UIFont systemFontOfSize:12];
        _label.backgroundColor = [UIColor colorWithRed:18/255.0  green:129/255.0  blue:201/255.0 alpha:1];
        _label.layer.cornerRadius = 8;
        _label.clipsToBounds = YES;
        _label.textAlignment = NSTextAlignmentCenter;
        _label.textColor= [UIColor whiteColor];
        [_yanzbutton addSubview:_label];
        _yanzbutton.userInteractionEnabled = NO;
    }
}
- (NSString *)md5:(NSString *)str
{
    const char *cStr = [str UTF8String];
    unsigned char result[16];
    CC_MD5(cStr, (CC_LONG)strlen(cStr), result); // This is the md5 call
    return [NSString stringWithFormat:
            @"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
            result[0], result[1], result[2], result[3],
            result[4], result[5], result[6], result[7],
            result[8], result[9], result[10], result[11],
            result[12], result[13], result[14], result[15]
            ];
}
- (IBAction)loginAction:(id)sender {
NSString *oldstring=[_originPassword.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
NSString *nowstring=[_resetPassword.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
NSString *nowstring2=[_repetNewPassword.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
if ([oldstring isEqualToString:@""]|| oldstring.length == 0) {
        [self.view makeToast:@"请输入验证码"];
}else if ([nowstring isEqualToString:@""]|| nowstring.length == 0) {
        [self.view makeToast:@"请输入新密码"];
}else if ([nowstring2 isEqualToString:@""]|| nowstring2.length == 0) {
        [self.view makeToast:@"请重新输入密码"];
}else{



  if ([_resetPassword.text isEqualToString:_repetNewPassword.text]) {

  [self loaddata];


  }else{

          [self.view makeToast:@"请确保两次输入的新密码一致!"];


  }



}





}
-(void)loaddata{
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];

 NSString *name = [[NSUserDefaults standardUserDefaults] objectForKey:@"userId"];
                NSString *password = [[NSUserDefaults standardUserDefaults] objectForKey:@"password"];
                      NSString *newpassword =  [ self md5:_resetPassword.text];

NSString *url = [NSString stringWithFormat:@"%@%@&code=%@&codeId=%@&password=%@&newPassword=%@",kchangedmiam,_name.text,_originPassword.text,_codeId,newpassword,newpassword];

      [httpTool ZBPostNetDataWith:url withDic:nil andSuccess:^(NSDictionary* dictionary){
              [MBProgressHUD hideAllHUDsForView:self.view animated:YES];

 if ([[NSString stringWithFormat:@"%@",dictionary[@"success"]]isEqualToString:@"true"]) {
         [self.view makeToast:@"更改成功!"];
     
                 [NSThread sleepForTimeInterval:1.0];

//                    [[NSUserDefaults standardUserDefaults] setObject:dictionary[@"password"] forKey:@"password"];
   UIStoryboard * storyBoard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
          DanLi *danli = [[DanLi alloc] init];
    danli.stay = @"no";
 OALoginViewController * loginVC =  [storyBoard instantiateViewControllerWithIdentifier:@"LoginVC"];
     [[NSUserDefaults standardUserDefaults] setObject:@"N" forKey:@"autoLogin"];
    self.view.window.rootViewController = loginVC;
     
}else{
 
        [self.view makeToast:@"更改失败"];

}

 }andFailure:^{
         [MBProgressHUD hideAllHUDsForView:self.view animated:YES];

        [self.view makeToast:@"更改失败"];

 }];
    
}



/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
